#include "pal/vz_app.h"
#include "CxlUtil.h"
#include "common/console.h"
#include "pal/vzCmdAdd.h"
#include "userLog.h"
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>

#define CAMDATAWITHPAI_DIR "/home/vmuser/work/robot/pyServer/camWPai"

static uv_loop_t *loop;
static uint8_t *buffer;

static bool isInitBuffer = false;

static uv_fs_t open_req;

static uv_fs_t read_req;

static uv_buf_t iov;

void on_read(uv_fs_t *req)
{
    if (req->result < 0)
    {
        LOG_ERROR("Read error: %s", uv_strerror(req->result));
    }
    else if (req->result == 0)
    {
        uv_fs_t close_req;
        // synchronous
        uv_fs_close(loop, &close_req, open_req.result, NULL);
    }
    else if (req->result > 0)
    {
        iov.len = req->result;
        // dispatchVzDataWithPai(&iov);
    }
}

void on_open(uv_fs_t *req)
{
    if (req->result >= 0)
    {
        iov = uv_buf_init(buffer, 1024 * 1024);
        uv_fs_read(loop, &read_req, req->result,
                   &iov, 1, -1, on_read);
    }
    else
    {
        LOG_ERROR("error opening file: %s", uv_strerror((int)req->result));
    }
}

static int CmdVzOpenWithPai(CONSOLE_CMD_PARAM_S *pParam, char *pAck)
{
    if (isInitBuffer == false)
    {
        buffer = (uint8_t *)malloc(1024 * 1024);
        memset(buffer, 0, 1024 * 1024);
        isInitBuffer = true;
    }
    uv_fs_open(loop, &open_req, CAMDATAWITHPAI_DIR, O_RDONLY, 0, on_open);
}

int vzCmdInit()
{
    // loop = getLoop();
}

int addVzCmd()
{
    // Console_CmdAdd("vzWihtPai", CmdVzOpenWithPai);
    // Console_CmdAdd("vzWihtPai", CmdVzOpenNoPai);
}
